import login from './login.js'
import { toast, jump } from '@/common/util'
import store from '@/store'
import { api, devApi } from '@/common/config'

const BASE_URL = uni.getAccountInfoSync().miniProgram.envVersion === 'release' ? api : devApi
// const BASE_URL = devApi
export default {
  // 配置请求参数
  config: {
    baseUrl: BASE_URL,
    header: {
      // 'Content-Type': 'application/json;charset=UTF-8',
      'Content-Type': 'application/x-www-form-urlencoded',
      'Authorization': 'Basic Z2FjOmdhYw=='
    },
    data: {},
    method: 'GET'
  },
  // 获取网络类型
  getNetwork() {
    return new Promise((resolve) => {
      uni.getNetworkType({
        complete: res => {
          resolve(res.networkType)
        }
      })
    })
  },
  async request(options = {}) {
    // const baseUrl = store.getters.baseUrl
    const loginToken = store.getters.token
    options.method = options.method || this.config.method
    options.dataType = options.dataType || this.config.dataType
    options.url = this.config.baseUrl + options.url
    options.header = options.header || this.config.header
    const network = await this.getNetwork()
    if (network && network === 'none') {
      toast('网络异常，请检查网络连接')
      return false
    } else {
      if (loginToken) {
        options.header = options.header || {
          'Content-Type': 'application/x-www-form-urlencoded'
        }
        options.header['Authorization'] = 'Bearer ' + loginToken
      }
      return uni.request(options)
    }
  },
  postForUpdateToken(url, data, options = {}) {
    options.url = url
    options.data = data
    options.method = 'POST'
    return this.request(options)
  },
  async updateAccessToken(force) {
    const refresh_token = store.getters.token
    if (!force) {
      const current = new Date()
      const expireTime = store.getters.expiresIn
      if (current.getTime() < expireTime) {
        return false
      }
    }

    if (!refresh_token) {
      login.removeLoginInfo()
      // toast('请先登录', () => {
      //   jump('/passport/password-login/password-login', 'reLaunch')
      // })
      return this.error()
    }

    const data = { grant_type: 'refresh_token', refresh_token }
    const [err, res] = await this.postForUpdateToken('/auth/oauth/token', data)
    if (res.data.code != 0) {
      login.removeLoginInfo()
      toast('登录超时，请重新登录', () => {
        jump('/passport/password-login/password-login', 'reLaunch')
      })
      return this.error()
    }
    login.saveLoginInfo(res)
    return true
  },
  async get(url, data, options = {}) {
    options.url = url
    options.data = data
    options.method = 'GET'
    options.noCheck = options.noCheck || true
    if (!options.noCheck) {
      await this.updateAccessToken(false)
    }
    return this.request(options)
  },
  async post(url, data, options = {}) {
    options.url = url
    options.data = data
    options.method = 'POST'
    if (!options.noCheck) {
      await this.updateAccessToken(false)
    }
    return this.request(options)
  },
  async del(url, data, options = {}) {
    options.url = url
    options.data = data
    options.method = 'DELETE'
    if (!options.noCheck) {
      await this.updateAccessToken(false)
    }
    return this.request(options)
  },
  async put(url, data, options = {}) {
    options.url = url
    options.data = data
    options.method = 'PUT'
    if (!options.noCheck) {
      await this.updateAccessToken(false)
    }
    return this.request(options)
  },
  // 上传图片
  async upload(url, options = {}) {
    await this.updateAccessToken(false)
    options.url = this.config.baseUrl + url
    options.fileType = options.fileType || 'image'
    options.formData = options.formData || {}
    options.filePath = options.filePath
    options.name = options.name || 'file'
    const loginToken = store.getters.token
    if (!loginToken) {
      options.header = options.header || this.config.header
      toast('请先登录', () => {
        jump('/passport/password-login/password-login', 'reLaunch')
      })
    } else {
      options.header = {
        'Authorization': 'Bearer ' + loginToken
      }
    }
    return uni.uploadFile(options)
  },
  // 下载图片
  async download(url, options = {}) {
    await this.updateAccessToken(false)
    options.url = this.config.baseUrl + url
    options.noCheck = options.noCheck || true
    const loginToken = store.getters.token
    if (!options.noCheck && !loginToken) {
      options.header = options.header || this.config.header
      toast('请先登录', () => {
        jump('/passport/password-login/password-login', 'reLaunch')
      })
      return false
    }
    if (loginToken) {
      options.header = options.header || {
        'Content-Type': 'application/x-www-form-urlencoded'
      }
      options.header['Authorization'] = 'Bearer ' + loginToken
    }
    return uni.downloadFile(options)
  },
  // 错误处理
  errorCheck(err, res, errfun = false) {
    if (err) {
      typeof errfun === 'function' && errfun()
      toast('加载失败')
      return false
    }
    if (res.data.code == '401') {
      typeof errfun === 'function' && errfun()
      login.removeLoginInfo()
      toast('登录超时，请重新登录', () => {
        jump('/passport/password-login/password-login', 'reLaunch')
      })
      return false
    } else if (res.data.code == '403') {
      typeof errfun === 'function' && errfun()
      login.removeLoginInfo()
      toast('访问受限', () => {
        // jump('/passport/password-login/password-login', 'reLaunch')
      })
      return false
    }
    if (res.data.code != 0 && res.data.code != 200) {
      if (res.data.msg == '订单金额不能为空,') {
        res.data.msg = '订单金额不能为空'
      }
      toast(res.data.msg || res.data.message)
      return false
    }
    return true
  },
  // 错误返回
  error() {
    return new Promise((resolve, reject) => {})
  }
}
